package 树;

public class 路径总和 {
    public class TreeNode {
       int val;
       TreeNode left;
       TreeNode right;
       TreeNode() {}
       TreeNode(int val) { this.val = val; }
       TreeNode(int val, TreeNode left, TreeNode right) {
           this.val = val;
           this.left = left;
           this.right = right;
       }
    }

    //函数定义:输入一个根节点，返回该根节点到叶子节点是否存在一条和为targetSum的路径
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if(root == null) return false;

        //分解问题：到最后每条路径的左右都是空，并且目标和应该为目标和减去一路上的根节点的值
        if(root.left == root.right && root.val == targetSum) return true;

        //递归去左子树和右子树进行每一条路径的判断
        return hasPathSum(root.left,targetSum - root.val) ||
                hasPathSum(root.right,targetSum - root.val);
    }

}
